#include "client.h"
#include "ui_client.h"

Client::Client(QWidget *parent,int uid) :
    QDialog(parent),
    ui(new Ui::Client)
{
    ui->setupUi(this);
    m_uid = uid;
    myDatabase.getConnection();

    QSqlQuery sql;
    sql.prepare("SELECT unickname,uaccount FROM tb_user WHERE uid = " + QString::number(m_uid));
    sql.exec();
    if(sql.first()){
        m_name = sql.value("unickname").toString();
        QString account = sql.value("uaccount").toString();
        sql.prepare("SELECT* FROM tb_user_VIP WHERE uaccount = " + account);
        sql.exec();
        if(sql.first()){
            m_name+="(VIP)";
            isVIP = true;
        }
    }
    else{
        sql.prepare("SELECT name FROM tb_admin WHERE id = " + QString::number(m_uid));
        sql.exec();
        if(sql.first()){
            m_name = sql.value("name").toString() +"（客服"+ QString::number(m_uid)+")";
        }
    }
    status = false;//初始化离线状态
    connect(&tcpSocket,SIGNAL(connected()),this,SLOT(onConnected()));
    connect(&tcpSocket,SIGNAL(disconnected()),this,SLOT(onDisconnected()));
    connect(&tcpSocket,SIGNAL(readyRead()),this,SLOT(onReadyRead()));
    connect(&tcpSocket,SIGNAL(errorOccurred(QAbstractSocket::SocketError)),this,SLOT(onError()));
}

Client::~Client()
{
    delete ui;
}
//发送消息槽函数
void Client::on_Send_clicked()
{
    QString msg = ui->Edit_message->text();
    if(msg == "")
        return;
    QTime time;
    msg = m_name + " "+time.currentTime().toString()+"\n" + msg;
    tcpSocket.write(msg.toUtf8());
    ui->Edit_message->clear();
}

//连接服务器槽函数
void Client::on_Connect_clicked()
{
    //离线点击则连接，在线点击则断开
    if(status == false){
        //获取服务器IP、Port、昵称
        serverIP.setAddress(ui->Edit_serverip->text());
        serverPort = ui->Edit_port->text().toShort();
        //连接请求，成功connected,失败error
        tcpSocket.connectToHost(serverIP,serverPort);
    }
    else{
        //向服务器发送离开聊天室的提示消息
        QString msg = username + "断开连接！";
        tcpSocket.write(msg.toUtf8());
        //关闭连接,发送信号disconnect
        tcpSocket.disconnectFromHost();
    }
}

//服务器连接成功时槽函数
void Client::onConnected(){
    status = true;
    //恢复按钮状态,禁用IP输入、连接
    ui->Send->setEnabled(true);
    ui->Edit_serverip->setEnabled(false);
    ui->Edit_port->setEnabled(false);
    ui->Connect->setText("disconnect");

    //向服务器发送进入聊天室提示消息
    QString msg = username + "连接成功！";
    //QString->QByteArray
    tcpSocket.write(msg.toUtf8());
}
//断开连接槽函数
void Client::onDisconnected(){
    status = false;
    //恢复按钮状态
    ui->Send->setEnabled(false);
    ui->Edit_serverip->setEnabled(true);
    ui->Edit_port->setEnabled(true);
    ui->Connect->setText("connect");

}
//接受消息槽函数
void Client::onReadyRead(){
    if(tcpSocket.bytesAvailable()){
        QByteArray buf = tcpSocket.readAll();
        //显示消息、回滚
        ui->listWidget->addItem(buf);
        ui->listWidget->scrollToBottom();
    }
}
//网络异常
void Client::onError(){
    QMessageBox::critical(this,"ERROR",tcpSocket.errorString());
}
